// component
var overlay;
var typed;
var themeColor;
var swiper;
(function() {
  marked.setOptions({breaks: true});
  overlay = new Overlay({
    closable: true,
    opened: false,
  });
  typed = new Typed('.typing-text', {
    string: [
      'web designer',
      'front end developer',
      'graphic designer',
      'photographer',
    ],
    typeSpeed: 120,
    loop: true,
  });
  themeColor = document.querySelectorAll('.theme-toggler span');
  for (const color of themeColor) {
    color.addEventListener('click', function(event) {
      let background = color.style.background;
      // $('body').attr('style', "background:" + background);
      document.querySelector('body').style.background = background;
    });
  }
  if (1 === window.performance.navigation.type) {
    let thisURL = document.URL;
    if (-1 !== thisURL.indexOf('#')) {
      $('.container').scrollTop(
        $(thisURL.substring(thisURL.indexOf('#'))).offset().top - 55,
      );
    }
  }
  initData();
  initEvent();
  return 0;
})();

function initData() {
  let path = '/';
  getList(path).then((data) => {
    initList(data);
  });
}

function getList(path) {
  return new Promise((resolve, reject) => {
    path = typeof path !== 'undefined' ? path : '/';
    const timestamp = 'timestamp=' + new Date()
      .getTime();
    $.ajax({
      type: 'GET',
      url: '/ls-l?' + timestamp + '&path=' + path,
      contentType: 'application/json',
      success: function(data) {
        if (data.success) {
          resolve(data.value);
        }
      },
    });
  });
}

function getFile(fn) {
  return new Promise((resolve, reject) => {
    const timestamp = 'timestamp=' + new Date().getTime();
    $.ajax({
      type: 'GET',
      url: '/file?' + timestamp + '&fn=' + fn,
      contentType: 'application/json',
      success: function(data) {
        resolve(data);
      },
    });
  });
}

function initList(data) {
  const fs = $('#fs');
  fs.empty();
  let fsWrapper = '<div class="swiper-wrapper">';
  for (const row of data) {
    fsWrapper += `<div class="swiper-slide box" data-fn="${row.fn}" data-s="${row.s}">`;
    let filename = row.fn.substring(row.fn.lastIndexOf('/') + 1);
    if ('d' === row.s) {
      fsWrapper += '<i class="fas fa-folder"></i>';
      fsWrapper += `<p> ${filename} </p>`;
    } else if ('-' === row.s || 'l' === row.s) {
      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      const fsCB = (fs, level) => {
        if (1024 > fs) return Math.floor(fs * 10) / 10 + ' ' + units[level];
        return fsCB(fs / 1024, level + 1);
      }
      let filesize = fsCB(row.fs, 0);
      fsWrapper += '<i class="fas fa-file"></i>';
      fsWrapper += `<p> ${filename} <span>${filesize}</span> </p>`;
    }
    fsWrapper += '</div>';
  }
  fsWrapper += '</div>';
  fs.html(fsWrapper);
  swiper = new Swiper('#fs', {
    loop: false,
    grabCursor: true,
    direction: 'vertical',
    breakpoints: {
      320: {
        slidesPerView: 10,
        spaceBetween: 10,
      },
      480: {
        slidesPerView: 3,
        spaceBetween: 30,
      },
      640: {
        slidesPerView: 8,
        spaceBetween: 10,
      },
    },
  });
  initSwiperEvent();
}

function initSwiperEvent() {
  $('#fs .box').unbind('click').bind('click', function(event) {
    event.stopPropagation();
    event.preventDefault();
    const s = $(this).data('s');
    const fn = $(this).data('fn');
    if ('d' === s) {
      getList(fn).then((data) => {
        data.unshift({
          fn: fn + '/..',
          s: 'd',
        });
        initList(data);
      });
    } else if ('-' === s || 'l' === s) {
      let filename = fn.substring(fn.lastIndexOf('/') + 1);
      let fileext = filename.substring(filename.lastIndexOf('.') + 1);
      // console.log(filename, fileext);
      if ('xlsx' === fileext) {
        const timestamp = 'timestamp=' + new Date().getTime();
        downloadFile('/file?' + timestamp + '&fn=' + fn, filename);
        return;
      }
      getFile(fn).then((data) => {
        if (
          'md' === fileext ||
          'txt' === fileext ||
          'log' === fileext ||
          'js' === fileext ||
          'pegjs' === fileext ||
          'properties' == fileext
        ) {
          overlay.content.innerHTML = marked.parse(data);
	  // console.log(data);
          let height = document.body.clientHeight * 0.8;
          let width = document.body.clientWidth * 0.8;
          overlay.content.style.height = height + 'px';
          overlay.content.style.width = width + 'px';
          overlay.open();
        }
      });
    }
  });
}

function initEvent() {
  $('#menu').unbind('click').bind('click', function(event) {
    event.stopPropagation();
    let header = document.querySelector('#header');
    header.classList.toggle('active');
  });
}

function downloadFile(uri, filename) {
  fetch(uri).then((res) =>
    res.blob().then((blob) => {
      let aEle = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      aEle.href = url;
      aEle.download = filename || new Date().getTime();
      aEle.click();
      window.URL.revokeObjectURL(url);
    }),
  );
}
